<template>
  <div class="uploadContent">
    <el-upload class="upload-demo" action="#" multiple :limit="limit" :accept="props.accept" :http-request="HttpRequest"
      :on-success="handleSuccess" :before-upload="handleBeforeUpload" :on-remove="handleRemove"
      :on-exceed="handleExceed" :show-file-list="false" list-type="picture" style="margin-right: 4px;margin-top: 3px;" :disabled="props.disabled">
      <el-button size="small" v-if="!props.disabled">
        <el-icon class="avatar-uploader-icon">
          <Upload />
        </el-icon></el-button>
    </el-upload>
    <template v-if="props.isImage">
      <el-image v-for="item in photos"
        style="width: 40px; height: 30px; margin-right: 5px; cursor: pointer; vertical-align: top" :src="convertUrl(item)"
        :zoom-rate="1.2" :max-scale="4" :min-scale="0.2" :preview-src-list="photosList" :initial-index="0"
        :preview-teleported="true" @show="clickImage" @switch="switchImage" fit="cover" />
    </template>
    <template v-else>
      <div :class="!isBreakLine?'break-line':''">
        <div v-for="(item,index) in recordData.photos"  :key="index">
          <div :class="props.isTable? 'pdf-item':'pdf-item1'" v-if="item&&docTypeList.includes(item.split('.').pop())"
            @mouseenter="mouseoverHandle(true)"  @mouseleave="mouseoverHandle(false)">
            <!-- <el-popconfirm title="Confirm to delete?" @confirm="deleteImageOk(index)" width="300" style="height: 200px;" v-if="props.isShowDel">
              <template #reference>
                <span :class="props.isTable? 'pdf-del':'pdf-del1'" v-if="isDel">×</span>
              </template>
            </el-popconfirm> -->
            <span :class="props.isTable? 'pdf-del':'pdf-del1'" @click="deleteImage(index)" v-if="isDel&&!disabled">
              <el-icon><Delete /></el-icon>
            </span>
            <a href="javascript:void(0)" @click="downloadPDF(item)">{{ getFileName(item) }}</a>
          </div>
          <div v-else>
            <el-image v-if="handleshowImg&&item" style="width: 40px; height: 30px; margin-right: 5px; cursor: pointer; vertical-align: top"
            :src="convertUrl(item)" :url-list="photosList" :zoom-rate="1.2" :max-scale="4" :min-scale="0.2" :initial-index="0"
            :preview-teleported="true" @show="clickImage" @switch="switchImage" :preview-src-list="photosList"
            fit="cover" />
          </div> 
        </div>
      </div>      
    </template>
	
	 <el-dialog v-model="visibleImage" width="500" @close="handleshowImg = true;" append-to-body>
      <p>Confirm to delete the select file?</p>
      <div style="text-align: right; margin: 0">
        <el-button size="small" text @click="visibleImage = false">cancel</el-button>
        <el-button size="small" type="primary" @click="deleteImageOk"> confirm </el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script setup lang="ts">
  import { ref, onMounted, nextTick, reactive, toRefs } from "vue";
  import service from "@/utils/request";
  import { ElNotification, ElMessage, UploadProps } from "element-plus";
  import {  ElMessageBox } from "element-plus"; 
  import {convertUrl} from "@/utils/tencentCos"; 
  import { downloadCosImg } from "@/utils/tencentCos";
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const emit = defineEmits(["onSuccess", "onDelete"]);
  const props = defineProps({
    photos: {
      type: Array,
      default: () => {
        return [];
      }
    },
    id: {
      type: [String, Number],
      default: ""
    },
    // 上传数量
    limit: {
      type: Number,
      default: 5
    },
    // 上传地址
    url: {
      type: String,
      default: ""
    },
    // 删除地址
    delUrl: {
      type: String,
      default: ""
    },
    //是否只支持图片
    isImage: {
      type: Boolean,
      default: false
    },
    //是否插入表格重
    isTable: {
      type: Boolean,
      default: true
    },
    //是否限制上传格式
    isAllAccept: {
      type: Boolean,
      default: false
    },
    record: {
      type: Object,
      default: () => {
        return {};
      }
    },
    //上传格式
    accept: {
      type: String,
      default: ".jpg,.png,.jpeg,.pdf,.PDF"
    },
    //上传格式
    dataName: {
      type: String,
      default: "id,"
    },
    //上传格式
    type: {
      type: String,
      default: ""
    },
    //是否展示删除
    isShowDel:{
      type: Boolean,
      default: true
    },
    //删除的时候是执行updatePhoto还是deleteFile 
    isDelSub:{
      type: Boolean,
      default: false
    },
    //是否上传前确认
    needConfirm: {
      type: Boolean,
      default: false
    },
    //是否展示预览
    isPreview: {
      type: Boolean,
      default: false
    },
    //是否换行
    isBreakLine: {
      type: Boolean,
      default: false
    },
    //是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
  });
  const handleshowImg = ref(true);
  const photosList = ref([])
  const docTypeList = ['pdf', 'xlsx', 'xls', 'docx', 'doc']
  const photosv = ref([]); 
  const recordData = ref({
		id: null,
		photos: []
	});
  watch(() => props.photos,
    val => {
      if (val.length==0||val==null) return;
      if (Array.isArray(val)) { 
      
        val.forEach(item => {
          if (item&&item!=' '&&item!="null") {
            if (!docTypeList.includes(item.split('.').pop())) {
              photosList.value.push(convertUrl(item))
            }
          }
        })
      } else {
        if (!docTypeList.includes(val.split('.').pop())) {
          photosList.value.push(convertUrl(val))
        }
      }
      if(typeof(props.photos[0])!="undefined"&&props.photos[0]!=" "&&props.photos[0]!="null"){
        photosv.value=props.photos
        recordData.value.photos=photosv.value
        recordData.value.id= props.id 
      }      
    }, {
    immediate: true
  }
  )  
	
	
	const loading = ref(false);  

  const isShowImage = ref(false);
  const photoList = ref([]);
  const handleBeforeUpload = file => {
    if (props.needConfirm) {
    return ElMessageBox.confirm('Confirm upload the file？', '提示', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        let type = file.name.split('.').pop()
        const maxSize = 3 * 1024 * 1024; // 10MB，根据你的需求设置最大文件大小
        if (file.size > maxSize) {
          ElMessage.warning(`File size ${maxSize / (1024 * 1024)}MB extends the limit`);
          return false;
        }
        if (!props.accept.split(',').includes('.' + type)) {
          ElMessage.warning(`Only support ${props.accept}`);
          return false;
        }
        return true;
      }).catch(() => {
        // 用户点击了取消，停止上传
        return false;
      });
    } else {
      let type = file.name.split('.').pop()
        const maxSize = 3 * 1024 * 1024; // 10MB，根据你的需求设置最大文件大小
        if (file.size > maxSize) {
          ElMessage.warning(`File size ${maxSize / (1024 * 1024)}MB extends the limit`);
          return false;
        }
        if (!props.accept.split(',').includes('.' + type)) {
          ElMessage.warning(`Only support ${props.accept}`);
          return false;
        }
        return true;
    }
  };
  const HttpRequest = async data => {
    loading.value = true;
    // new 一个formdata 对象 将我们的参数和文件赋值进去
    const formdata = new FormData();
    formdata.append("file", data.file);
    let typeList = props.dataName.split(',') 
    typeList.forEach(item => {
      formdata.append(item, item == 'ids' ? props.id : props[item]);
    })
    let res = await service.post(props.url, formdata); 
    if (Array.isArray(res.data)) { 
      photoList.value=res.data.map(item=>{return item.url})
      recordData.value.photos=res.data.map(item=>{return item.url})
      handleSuccess()
    } else {
      if (props.limit == 1 && props.photos.length > 0) {
        photoList.value.splice(0, 1, res.data.url);
        recordData.value.photos.splice(0, 1, res.data.url);
        handleSuccess()
      } else {
        photoList.value.push(res.data.url);
        recordData.value.photos.push(res.data.url);
      }
    }
  };
  function clickImage() { 
    nextTick(() => {
      let wrapper = document.getElementsByClassName("el-image-viewer__actions__inner");
      // 添加下载图片按钮
      let downloadBtn = document.createElement("i");
      downloadBtn.setAttribute("class", "el-icon");
      downloadBtn.innerHTML =
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M160 832h704a32 32 0 1 1 0 64H160a32 32 0 1 1 0-64m384-253.696 236.288-236.352 45.248 45.248L508.8 704 192 387.2l45.248-45.248L480 584.704V128h64z"></path></svg>';
      downloadBtn.addEventListener("click", cusClickHandler); 

      wrapper[0].appendChild(downloadBtn);

      // 添加删除图片按钮
      let deleteBtn = document.createElement("i");
      deleteBtn.setAttribute("class", "el-icon");
      deleteBtn.innerHTML =
        ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M352 192V95.936a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32V192h256a32 32 0 1 1 0 64H96a32 32 0 0 1 0-64zm64 0h192v-64H416zM192 960a32 32 0 0 1-32-32V256h704v672a32 32 0 0 1-32 32zm224-192a32 32 0 0 0 32-32V416a32 32 0 0 0-64 0v320a32 32 0 0 0 32 32m192 0a32 32 0 0 0 32-32V416a32 32 0 0 0-64 0v320a32 32 0 0 0 32 32"></path></svg>';

      deleteBtn.addEventListener("click", deleteImage);
      wrapper[0].appendChild(deleteBtn);
    });
  }
  function cusClickHandler() {
    const imgUrl = recordData.value.photos[imgIndex.value];
    downloadCosImg(imgUrl, getFileName(imgUrl));
  }
  
	function downloadPDF(url:string) {
    if(props.isPreview){
      let isDown=['pdf','docx','doc','xls','xlsx','txt'].some((item) => url.includes(item))
     url =encodeURI(convertUrl(url))
      if(isDown){
        window.open(router.resolve({ path: '/pdfView/index', query: { pdfUrl: url} }).href, '_blank')
      }else{
        downLoadHandle(url)
      }
    }else{
      downLoadHandle(url)
    }
	  
	}
  const downLoadHandle=(url)=>{
    ElMessageBox.confirm("Confirm to Download the file？", "Download  Information", {
		type: "warning",
		confirmButtonText: "Confirm",
		cancelButtonText: "Cancel",
	  }).then(async () => {
      const newUrl = convertUrl(url);
			const a = document.createElement('a'); 
			a.href = newUrl;
			a.download = getFileName(newUrl);
			a.click();
  })
}

  const imgIndex = ref(0);
  function switchImage(e) {
    imgIndex.value = e;
  }
  const visibleImage = ref(false);
  const isPdfDel = ref(false)
  const deleteImage = async () => {
    isPdfDel.value = false
    //visibleImage.value = true;
    //handleshowImg.value = false;

	  ElMessageBox.confirm("Confirm to Delete the file？", "Delete  Information", {
		type: "warning",
		confirmButtonText: "Confirm",
		cancelButtonText: "Cancel",
		modalClass:"imageUploadDelete"
	  }).then(async () => {
          deleteImageOk()

	  });

  };
  const handleExceed = (files, uploadFiles) => {
    if (props.limit == 1) {
      HttpRequest({ file: files[0] })
    }
  }
  const handleRemove = (file, fileList) => {
    photoList.value = photoList.value.filter(item => item.url != file.url);
  };
 
  const deleteImageOk = async () => { 
    let url=recordData.value.photos[imgIndex.value]
    recordData.value.photos.splice(imgIndex.value, 1)  
    if(props.isDelSub) {
      emit("onDelete", {...recordData.value, delfile: recordData.value.photos[imgIndex.value],url:url});
    } else {
      recordData.value.photos.splice(imgIndex.value, 1)
      emit("onSuccess", recordData.value);
    }
    // // @ts-ignore
    // ElNotification.success({
    //   title: "Prompt information",
    //   message: "delete successful!",
    //   position: "bottom-right"
    // });
    visibleImage.value = false;
  };
  // 获取文件名称
  function getFileName(name) { 
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
  }
  // 上传成功回调
  const handleSuccess = () => {
    emit("onSuccess", recordData.value);
  };

  //删除
  const isDel = ref(false)
  //防抖函数
  const debounce = (fn, t) => {
    let delay = t || 300
    let timer
    return function () {
      let args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (callNow) fn.apply(this, args)
    }
  }
  const mouseoverHandle = debounce((status) => {
    isDel.value = status
  }, 500)

</script>
<style scoped lang="scss">
  .el-image-viewer__wrapper {
    /* 修改遮罩层的样式 */
    width: 60%;
    height: 60%;
    left: 20%;
    top: 20%;
  }

  .upload-demo {
    display: inline-block;
  }

  .uploadContent {
    display: flex;
  }

  .pdf-item1 {
    display: flex;
    position: relative;
    border: 1px solid #ccc;
    height: 24px;
    border-radius: 2px;
    margin-top: 4px;
    margin-right: 2px;
    line-height: 24px;
    padding: 0 10px 0 16px;
    font-size: 12px;
  }

  .pdf-del1 {
    font-size: 14px;
    position: absolute;
    left: 0px;
    top: 2px;
    width: 8px;
    height: 8px;
    cursor: pointer;
  }

  .pdf-item {
    display: flex;
    position: relative;
    padding: 0 6px;
    padding-left: v-bind('props.isShowDel?"20px":"6px"');
    border: 1px solid #ccc;
    height: 24px;
    border-radius: 2px;
    margin-top: 4px;
    margin-right: 2px;
  }

  .pdf-del {
    font-size: 30px;
    position: absolute;
    left: 0px;
    width: 8px;
    height: 8px;
    color: #ff9e40;
    cursor: pointer;
  }
  .break-line{
    display: flex;
  }
</style>

<style>
  .imageUploadDelete{
      z-index:9999 !important;
  }
</style>